
//
//  DataFetch.m
//  DianYingKe
//
//  Created by Blackie on 15/11/23.
//  Copyright © 2015年 Blackie. All rights reserved.
//

#import "DataFetch.h"

@implementation DataFetch

/**
 * 获取缓存+请求数据（不解析数据）
 */
+ (void)getWithApi:(NSString *)api Dic:(NSMutableDictionary*)dic Completion:(void(^)(NSURLSessionDataTask *operation, id resultObj,NSString*link))completion Cache:(void(^)(id cacheObj))cache Fail:(void(^)(NSString* reason))fail
{
        NSLog(@"+++++++++++%@",api);
    NSString *filepath = [GetCacheDataDir() stringByAppendingPathComponent:[api fileNameMD5WithExtension:@"json"]];
    // 读取缓存
    NSData *data = [NSData dataWithContentsOfFile:filepath];
    if ([data isKindOfClass:[NSData class]]) {
        cache([NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
    }
    
    // 请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
//    NSArray *arrContentTypes = @[@"text/plain",
//                                 @"text/html",
//                                 @"text/json",
//                                 @"text/javascript"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html", @"text/json", nil];
//    responseSerializer.acceptableContentTypes = [NSMutableSet setWithArray:arrContentTypes];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer.timeoutInterval = 10;
    
    [manager GET:api parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSLog(@"+++++++++++%@",api);
            completion(task, responseObject,api);
        }
        else {
            NSData *data = (NSData*)responseObject;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            [data writeToFile:filepath atomically:NO];
            if (result) {
                if ([result[@"sta"] isEqualToString:@"1"]) {
                    fail(result[@"msg"]);
                }
                else{
                    completion(task, result,api);
                }
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSData *data = [NSData dataWithContentsOfFile:filepath];
//        if (data) {
//            completion(task, [NSJSONSerialization JSONObjectWithData:data options:0 error:nil],api);
//        }
        
    }];
    
}
+ (void)postWithApi:(NSString *)api Dic:(NSMutableDictionary*)dic Completion:(void(^)(NSURLSessionDataTask *operation, id resultObj,NSString*link))completion Cache:(void(^)(id cacheObj))cache Fail:(void(^)(NSString* reason))fail
{
    NSLog(@"+++++++++++%@",api);
    NSString *filepath = [GetCacheDataDir() stringByAppendingPathComponent:[api fileNameMD5WithExtension:@"json"]];
    // 读取缓存
    NSData *data = [NSData dataWithContentsOfFile:filepath];
    if ([data isKindOfClass:[NSData class]]) {
        cache([NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
    }
    
    // 请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html", @"text/json", nil];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer.timeoutInterval = 10;
    

    
         [manager POST:api parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                NSLog(@"+++++++++++%@%@",api,dic);
                completion(task, responseObject,api);
            }
            else {
                NSData *data = (NSData*)responseObject;
                NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                if (result) {
                    if ([result[@"sta"] intValue]== 1) {
                        fail(result[@"msg"]);
                    }
                    else{
                        completion(task, result,api);
                    }
                }
            }
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    
}

/**
 *  读取本地数据
 *
 *  @param api        请求接口
 *  @param completion 本地缓存
 *  @param failed     请求失败
 *  @return 返回请求接口
 */
+ (void)fetctCacheWithApi:(NSString *)api Complition:(void(^)(NSArray *arrResult, NSString *api))completion failed:(void(^)(NSError *error, NSString *api))failed
{
//    NSString *filepath = [GetCacheDataDir() stringByAppendingPathComponent:[api fileNameMD5WithExtension:@"json"]];
//    NSData *dataResult = [NSData dataWithContentsOfFile:filepath];
    
//    if ([dataResult isKindOfClass:[NSData class]]) {
//        NSMutableArray *arrResult = [NSMutableArray array];
//        
//        NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:dataResult options:0 error:nil];
//        if ([responseObject isKindOfClass:[NSDictionary class]]) {
//            NSArray *arrDict = responseObject[@"item_list"];
//            for (NSDictionary *dict in arrDict) {
//                if ([[dict allKeys] count] > 3) {
//                    UTAModel *model = [UTAModel modelWithDictionary:dict];
//                    [arrResult addObject:model];
//                }
//            }
//        }
//        completion(arrResult, api);
//    }
//    else {
//        failed((NSError *)dataResult, api);
//    }
}

/**
 *  请求接口数据
 *
 *  @param api        请求接口
 *  @param completion 请求数据
 *  @param failed     请求失败
 *
 *  @return
 */
+ (void)fetctRequestWithApi:(NSString *)api Complition:(void(^)(NSArray *arrResult, NSString *api))completion failed:(void(^)(NSError *error, NSString *api))failed
{
    void (^resolve)(id)=^(id dataResult) {
        
        if (![dataResult isKindOfClass:[NSData class]]) {
            completion(nil, api);
            return;
        }
        
        NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:dataResult options:0 error:nil];
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSMutableArray *arrResult = [NSMutableArray array];
            
//            NSArray *arrDict = responseObject[@"item_list"];
//            for (NSDictionary *dict in arrDict) {
//                if ([[dict allKeys] count] > 3) {
//                    NSDictionary *diction = [NSDictionary dictionaryWithDictionary:dict];
//                    ModelSite *model = [[ModelSite alloc]initWithDict:diction];
//                    [arrResult addObject:model];
//                }
//            }
            completion(arrResult, api);
        }
        else {
            failed((NSError *)dataResult, api);
        }
    };
    
    NSString *filepath = [GetCacheDataDir() stringByAppendingPathComponent:[api fileNameMD5WithExtension:@"json"]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    NSArray *arrContentTypes = @[@"text/plain",
                                 @"text/html",
                                 @"text/json",
                                 @"text/javascript"];
    responseSerializer.acceptableContentTypes = [NSMutableSet setWithArray:arrContentTypes];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer.timeoutInterval = 10;
    
    [manager GET:api parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData * data = (NSData *)responseObject;
        if (data) {
            [data writeToFile:filepath atomically:NO];
        }
        resolve(data);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = [NSData dataWithContentsOfFile:filepath];
        resolve(data);
    }];
    
    //    [manager GET:api parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        NSData * data = (NSData *)responseObject;
    //        if (data) {
    //            [data writeToFile:filepath atomically:NO];
    //        }
    //        resolve(data);
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        NSData *data = [NSData dataWithContentsOfFile:filepath];
    //        resolve(data);
    //    }];
}



+ (void)fetctKeyWordsRequestWithApi:(NSString *)api Complition:(void(^)(NSString *arrResult, NSString *api))completion failed:(void(^)(NSError *error, NSString *api))failed
{
    void (^resolve)(id)=^(id dataResult) {
        
        if (![dataResult isKindOfClass:[NSData class]]) {
            completion(nil, api);
            return;
        }
        
        NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:dataResult options:0 error:nil];
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            //            NSMutableArray *arrResult = [NSMutableArray array];
            
            NSString *arrDict = responseObject[@"keywords"];
            completion(arrDict, api);
        }
        else {
            failed((NSError *)dataResult, api);
        }
    };
    
    NSString *filepath = [GetCacheDataDir() stringByAppendingPathComponent:[api fileNameMD5WithExtension:@"json"]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    NSArray *arrContentTypes = @[@"text/plain",
                                 @"text/html",
                                 @"text/json",
                                 @"text/javascript"];
    responseSerializer.acceptableContentTypes = [NSMutableSet setWithArray:arrContentTypes];
    manager.responseSerializer = responseSerializer;
    manager.requestSerializer.timeoutInterval = 10;
    
    [manager GET:api parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData * data = (NSData *)responseObject;
        if (data) {
            [data writeToFile:filepath atomically:NO];
        }
        resolve(data);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = [NSData dataWithContentsOfFile:filepath];
        resolve(data);
    }];
}
@end
